package com.song.service.file;

import com.song.common.Result;
import com.song.entity.Constants;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service("fileService")
public class FileServiceImpl implements FileService {

    @Value("${file.upload-path}")
    private String fileUploadPath;

    /**
     * 上传文件
     */
    @Override
    public Result upload(MultipartFile file) {
        Result result = new Result();
        if (file.isEmpty()) {
            result.setCode(Constants.FAIL_CODE);
            result.setMsg("上传文件为空！");
            return result;
        }
        File dest = new File(fileUploadPath);
        if (!dest.exists()) {
            dest.mkdir();
        }
        try {
            File destFile = executeUpload(file);
            result.setCode(Constants.SUCCESS_CODE);
            result.setMsg("上传文件成功！");
            result.setData(destFile);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(Constants.FAIL_CODE);
            result.setMsg("上传文件失败！");
        }
        return result;
    }

    /**
     * 上传多文件
     */
    @Override
    public Result uploadFiles(MultipartFile[] file) {
        Result result = new Result();
        if (file == null || file.length == 0) {
            result.setCode(Constants.FAIL_CODE);
            result.setMsg("上传文件为空！");
            return result;
        }
        File dest = new File(fileUploadPath);
        if (!dest.exists()) {
            dest.mkdir();
        }
        for (int i = 0; i < file.length; i++) {
            try {
                if (file[i] != null) {
                    executeUpload(file[i]);
                }
            } catch (Exception e) {
                e.printStackTrace();
                result.setCode(Constants.FAIL_CODE);
                result.setMsg("第 "+ i+1 +" 个文件上传失败！");
                return result;
            }
        }
        result.setCode(0);
        return result;
    }

    /**
     *  上传文件
     */
    private File executeUpload(MultipartFile file) throws Exception {
        //文件后缀名
        String fileName = file.getOriginalFilename();
        File dest = new File(fileUploadPath + fileName);
        file.transferTo(dest);
        return dest;
    }

}
